package com.example.actionsignin.dialog;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.example.actionsignin.R;
import com.example.actionsignin.mvp.presenter.IImageListener;
import com.example.actionsignin.utils.ImageUtils;
import com.example.actionsignin.utils.PermissionUtil;
import com.example.actionsignin.utils.ToastUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.content.ContentValues.TAG;

/**
 * Created by 旭 on 2017/7/29/029.
 */

public class AddCameraDialogFragment extends DialogFragment implements View.OnClickListener {

    private View view;

    private IImageListener listener = null;

    private String mFileName;

    @Override
    public void onStart() {
        super.onStart();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        getDialog().getWindow().setLayout(displayMetrics.widthPixels, getDialog().getWindow().getAttributes().height);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(STYLE_NO_TITLE);

        Window window = getDialog().getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.gravity = Gravity.BOTTOM;
        layoutParams.windowAnimations = R.style.BottomDialogAnimation;
        window.setAttributes(layoutParams);

        view = inflater.inflate(R.layout.fragment_dialog_add_camera, container, false);

        listener = (IImageListener) getActivity();
        init();

        return view;
    }

    private void init() {
        view.findViewById(R.id.add_camera_1).setOnClickListener(this);
        view.findViewById(R.id.add_camera_2).setOnClickListener(this);
        view.findViewById(R.id.add_camera_3).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.add_camera_1:
                if (PermissionUtil.isPermissions(getActivity(),Manifest.permission.READ_EXTERNAL_STORAGE, 1)) {
                    openPhotos();
                }
                break;
            case R.id.add_camera_2:
                if (PermissionUtil.isPermissions(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE, 2)) {
                    openCamera();
                }
                break;
            case R.id.add_camera_3:
                dismiss();
                break;
        }
    }

    private void openCamera()
    {
        if (PermissionUtil.isPermissions(getActivity(),Manifest.permission.CAMERA, 3))
        {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                String fileName = getFileName();
                intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(fileName)));
                startActivityForResult(intent, 2);
            } else {
                ToastUtil.INSTANCE(getActivity(), "内存不可用");
            }
        }
    }

    private String getFileName()
    {
        String saveDir = Environment.getExternalStorageDirectory().getPath() + "/sign_Photos";
        File dir = new File(saveDir);
        if (!dir.exists()) {
            dir.mkdir();
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddssSSS");
        String filename = saveDir + "/MT" + (format.format(new Date())) + ".jpg";
        mFileName = filename;

        Log.d(TAG, "getFileName: " + filename);

        return filename;
    }

    private void openPhotos() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {
                case 1:
                    doOpenPhoto(data);
                    dismiss();
                    break;
            }
        }

        if (requestCode == 2)
        {
            listener.setImagePath(downUpPhoto(mFileName));
            dismiss();
        }
    }

    private void doOpenPhoto(Intent data)
    {
        Uri selectImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(selectImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        listener.setImagePath(downUpPhoto(picturePath));
    }

    private String downUpPhoto(String path)
    {
        String filePath = "";

        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        //缩放图片
        bitmapOptions.inSampleSize = 8;
        int degree = ImageUtils.readPictureDegree(path);
        Bitmap bitmap = BitmapFactory.decodeFile(path,bitmapOptions);
        //旋转图片操作
        bitmap = ImageUtils.rotaingImageView(degree,bitmap);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);

        String savePath = Environment.getExternalStorageDirectory().getPath() + "/sign_Photos";
        File file = new File(savePath);
        if (!file.exists())
        {
            file.mkdir();
        }
        FileOutputStream fileOutputStream = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddssSSS");
        String fileName = "MT" + simpleDateFormat.format(new Date()) + ".jpg";
        File file1 = new File(savePath,fileName);
        try {
            fileOutputStream = new FileOutputStream(file1);
            try {
                fileOutputStream.write(byteArrayOutputStream.toByteArray());
            } catch (IOException e) {
                e.printStackTrace();
            }
            filePath = file1.getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            if (fileOutputStream != null)
            {
                try {
                    byteArrayOutputStream.flush();
                    byteArrayOutputStream.close();
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    bitmap.recycle();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return filePath;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openPhotos();
                } else {
                    ToastUtil.INSTANCE(getActivity(), "无权限");
                }
                break;
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                } else {
                    ToastUtil.INSTANCE(getActivity(), "无权限");
                }
                break;
            case 3:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
                } else {
                    ToastUtil.INSTANCE(getActivity(), "无权限");
                }
                break;
        }
    }
}
